//
//  ZYCTeachingAttendanceEvaluateViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/29.
//

#import "ZYCTeachingAttendanceEvaluateViewController.h"
#import "ZYCAttendanceCommentCell.h"
#import "ZYCAttendanceEvaluateBottomView.h"
#import "ZYCTeachingEvaluatedDetailModel.h"
#import "ZYCTeachingEvaluatedSubmitModel.h"
#import "ZYCUserLoginModel.h"

#define bottomHeight 350.f
@interface ZYCTeachingAttendanceEvaluateViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ZYCTeachingEvaluatedDetailModel *detailModel;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) NSMutableDictionary *dataDict;
@property (nonatomic, strong) ZYCAttendanceEvaluateBottomView *bottomView;
@property (nonatomic, strong) NSMutableArray *selectResultArr;
@property (nonatomic, strong) NSArray *localSaveArr;



@end

@implementation ZYCTeachingAttendanceEvaluateViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [self createCurrentPaperFilePath];
    if ([fileManager fileExistsAtPath:filePath]) {
        self.localSaveArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        [self.selectResultArr addObjectsFromArray:self.localSaveArr];
    }
    
    NSString *remark =  [[NSUserDefaults standardUserDefaults] objectForKey:self.listenClassId];
    self.bottomView.remark = remark;
    
    self.title = @"评课";
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.bottomView;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self loadEvaluationEditDetail];
}






#pragma mark - 网络请求
// 评价详情
- (void)loadEvaluationEditDetail{
    NSDictionary *params = @{
        @"listenClassId":self.listenClassId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeachAttendanccGetSchemaListById requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                self.detailModel = [ZYCTeachingEvaluatedDetailModel yy_modelWithDictionary:responseObject[@"body"]];
                NSInteger sum = 0;
                for (ZYCTeachingEvaluatedSingleModel *model in self.detailModel.schemeProjectList) {
                    for (ZYCTeachingEvaluatedSubmitModel *m in self.localSaveArr) {
                        if ([m.schemeProjectId isEqualToString:model.schemeProjectId]) {
                            if (m.score.length > 0){
                                sum += [m.score integerValue];
                                model.doScore = m.score;
                            }
                        }
                    }
                }
                self.bottomView.score = [NSString stringWithFormat:@"%ld",sum];
                [self.tableView reloadData];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

//  点击提交
- (void)clickRightItem:(UIButton *)sender{
    for (ZYCTeachingEvaluatedSingleModel *model in self.detailModel.schemeProjectList) {
        if (model.doScore.length == 0) {
            [MrjToast makeToast:@"您还有选项没打分" makeView:self.view];
            return;;
        }
    }
    if (self.bottomView.content.length == 0) {
        [MrjToast makeToast:@"请输入评价内容" makeView:self.view];
        return;
    }
    [self addEvalution];
    
}



// 评价
-(void)addEvalution{
    
    NSMutableArray *temp =[NSMutableArray arrayWithCapacity:0];
    for (ZYCTeachingEvaluatedSubmitModel *model in self.selectResultArr) {
        NSMutableDictionary *dict = [model yy_modelToJSONObject];
        [temp addObject:dict];
    }
    NSDictionary *params = @{
        @"listenClassId":self.listenClassId,
        @"content":self.bottomView.content,
        @"classEvaluateItemList":temp
    };
    
    [MrjSVProgressHUD showWithStatus:@"提交中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeachAttendanccAddEvalution requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"body"]];
                
                [self clean];
                
                [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:self.listenClassId];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
            
        } failure:^(NSError * _Nonnull error) {
            [MrjToast makeToast:@"提交失败" makeView:self.view];
        }];
}
// 提交成功后删除缓存
- (void)clean{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [self createCurrentPaperFilePath];
    [fileManager removeItemAtPath:filePath error:nil];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.detailModel.schemeProjectList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCAttendanceCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCAttendanceCommentCell class]) forIndexPath:indexPath];

    ZYCTeachingEvaluatedSingleModel *model = self.detailModel.schemeProjectList[indexPath.section];
    ZYCWeakSelf
    cell.model = model;
    cell.saveBlock = ^(ZYCTeachingEvaluatedSingleModel * _Nonnull model, NSString * _Nonnull text) {
        model.doScore = text;
        ZYCTeachingEvaluatedSubmitModel *m = [[ZYCTeachingEvaluatedSubmitModel alloc] init];
        m.schemeProjectId = model.schemeProjectId;
        m.project = model.project;
        m.score = text;

        if (self.selectResultArr.count > 0) {
            [self.selectResultArr enumerateObjectsUsingBlock:^(ZYCTeachingEvaluatedSubmitModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([m.schemeProjectId isEqualToString:obj.schemeProjectId]) {
                    [self.selectResultArr removeObject:obj];
                    [self.selectResultArr addObject:m];
                    *stop = NO;
                }else{
                    [self.selectResultArr addObject:m];
                    *stop = NO;
                    return;
                }
            }];
        }else{
            [self.selectResultArr addObject:m];
        }
        
//        NSLog(@"存储的数据:%@",self.selectResultArr);
        NSString *filePath = [self createCurrentPaperFilePath];
        BOOL isSuccess =  [NSKeyedArchiver archiveRootObject:self.selectResultArr toFile:filePath];
//        NSLog(@"%@",isSuccess ? @"成功" : @"失败");
        
        NSInteger sum = 0;
        for (ZYCTeachingEvaluatedSubmitModel *scoreModel in self.selectResultArr) {
            sum += [scoreModel.score integerValue];
        }
        
        weakSelf.bottomView.score = [NSString stringWithFormat:@"%ld",sum];


    };

    return cell;
}

- (NSString *)createCurrentPaperFilePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    ZYCUserLoginModel *userLogin = [ZYCUserLoginModel userLogin];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *userIdDirectryPath = [documentPath stringByAppendingPathComponent:userLogin.userId];
    // 创建文件夹(用户ID)
    [fileManager createDirectoryAtPath:userIdDirectryPath withIntermediateDirectories:YES attributes:nil error:nil];
    // 听评课路径
    NSString *attendancePath = [userIdDirectryPath stringByAppendingPathComponent:@"attendance"];
    // 创建文件夹(听评课)
    [fileManager createDirectoryAtPath:attendancePath withIntermediateDirectories:YES attributes:nil error:nil];
    // 试卷ID路径
    NSString *filePath = [attendancePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.data",self.listenClassId]];
    return filePath;
}

- (BOOL)array:(NSArray *)array1 isEqualTo:(NSArray *)array2 {
    if (array1.count != array2.count) {
        return NO;
    }
    for (NSString *str in array1) {
        if (![array2 containsObject:str]) {
            return NO;
        }
    }
    for (NSString *str in array2) {
        if (![array1 containsObject:str]) {
            return NO;
        }
    }
    return YES;
    
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


#pragma mark - getters
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCAttendanceCommentCell class] forCellReuseIdentifier:NSStringFromClass([ZYCAttendanceCommentCell class])];
        _tableView.estimatedRowHeight = 213;
        _tableView.rowHeight = UITableViewAutomaticDimension;
    }
    return _tableView;
}

- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [[UIButton alloc] init];
        [_rightButton setTitle:@"提交" forState:UIControlStateNormal];
        [_rightButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _rightButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_rightButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}


- (ZYCAttendanceEvaluateBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[ZYCAttendanceEvaluateBottomView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, bottomHeight)];
        _bottomView.saveBlock = ^(NSString * _Nonnull content) {
            [[NSUserDefaults standardUserDefaults] setObject:content forKey:self.listenClassId];
            [[NSUserDefaults standardUserDefaults] synchronize];
        };
    }
    return _bottomView;
}

- (NSMutableArray *)selectResultArr {
    if (!_selectResultArr) {
        _selectResultArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectResultArr;
}

- (NSMutableDictionary *)dataDict {
    if (!_dataDict) {
        _dataDict = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    return _dataDict;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
